//
//  HRUserAccountViewModel.swift
//  microBlog
//
//  Created by HR_W on 16/5/22.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit

private let userInfoKey = "com.wanghaorui.userInfoKey"

class HRUserAccountViewModel: NSObject {
    //单例对象
    static let shareAccountViewModel:HRUserAccountViewModel = HRUserAccountViewModel()
    
    var userAccount :HRUserAccount?
    
    //重写构造方法 在构造方法中 加载用户的账户模型
    //加private 成为真正的单例
    private override init() {
        super.init()
        
        userAccount = loadUserAccount()
    }
    //通过判断用户是否登录的计算型属性 来解决每次都要判断的问题
    //计算型属性 每次调用都会执行
    var userLogin: Bool{
    
        if userAccount?.exrires_data?.compare(NSDate()) == .OrderedDescending {
            return true
        }
        //如果过期 需要将userAccount置为nil
        userAccount = nil
        return false
    }
    var headURL: NSURL? {
    
        get {
            return NSURL(string: userAccount?.avatar_large ?? "")
        }
    
    }
    
 
}

extension HRUserAccountViewModel {
    //使用code 加载用户授权的token(令牌)
    func loadAccessToken(code: String, finished: (isSuccess: Bool)->()) {
   // print("++++"+code)
      
        HMNetworkTools.sharedTools.loadAccessToken(code) { (responseObject, error) in
            //请求token成功后 使用token 和uid 获取用户信息
            if error != nil {
            finished(isSuccess: false)
            return
            }
         // print("成功了")
            self.loadUserInfo(responseObject, finished: finished)
        }
        
    
    }
    //请求用户信息
    private func loadUserInfo(response: AnyObject?,finished: (isSuccess: Bool)->()){
    
        guard let result = response as? [String: AnyObject] else {
            finished(isSuccess: false)
            return
        }

        HMNetworkTools.sharedTools.loadUserInfo(result){ (responseObject, error) in
            
            if error != nil {
                finished(isSuccess: false)
                return
            }
            
            guard var dict = responseObject as? [String: AnyObject] else {
            finished(isSuccess: false)
                return
            }
            //用户信息 就应该保存用户信息到本地
            //合并两个字典 统一保存用户数据到本地
            for (key,value) in result {
            
                dict[key] = value
                
            }
            //保存数据
            self.saveUserAccount(dict)
            finished(isSuccess: true)
        }
    }
}

//存取数据
extension HRUserAccountViewModel {

    func saveUserAccount(dict: [String: AnyObject]) {
    //使用偏好设置 保存字典数据
        
        //1.将dict 转为 模型对象
        let user = HRUserAccount(dict: dict)
        
        self.userAccount = user
        //2.将模型对象转为字典
        let keys = ["access_token","uid","name","avatar_large","expires_in","exrires_data"]
       
        let userInfo = user.dictionaryWithValuesForKeys(keys)
         //3.保存字典数据
        let userDefaults = NSUserDefaults.standardUserDefaults()
        //不能够向 偏好设置中保存 nil
        userDefaults.setObject(userInfo, forKey: userInfoKey)
        //同步
        userDefaults.synchronize()
        
         print(NSHomeDirectory())
    }
    
    func loadUserAccount() -> HRUserAccount? {
    
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String: AnyObject] else {
        
            return nil
        }
        
        let user = HRUserAccount(dict: dict)
        
        return user
        
    
    }

}
